package com.real.fact.web.sale.application;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.real.fact.web.application.AbstractPagedListCommand;
import com.real.fact.web.sale.domain.Sale;
import com.real.fact.web.sale.domain.SaleFilter;
import com.real.fact.web.sale.domain.SaleRepository;
import com.real.fact.web.sale.domain.Ticket;

/**
 * 
 */
public class ListSalesCommand extends AbstractPagedListCommand<Sale> {

  private final SaleRepository saleRepository;

  private Date dateFrom;

  private Date dateEnd;

  private boolean facturaA;

  private boolean facturaB;

  private boolean remito;

  private boolean noFact;
  
  private String payedOption = SaleFilter.PayedFilter.BOTH.toString();

  public ListSalesCommand(SaleRepository saleRepository) {
    super();
    this.saleRepository = saleRepository;
  }

  public List<Sale> execute() {
    SaleFilter filter = new SaleFilter(dateFrom, dateEnd);
    if (facturaA) {
      filter.addTicketType(Ticket.A);
    }
    if (facturaB) {
      filter.addTicketType(Ticket.B);
    }
    if (remito) {
      filter.addTicketType(Ticket.R);
    }
    if (noFact) {
      filter.addTicketType(Ticket.NONE);
    }
    filter.setPayedOption(SaleFilter.PayedFilter.valueOf(payedOption));
    return saleRepository.filter(getPaging(), filter);
  }

  public void setDateFrom(final Date dateFrom) {
    this.dateFrom = sanitizeFromDate(dateFrom);
  }

  public void setDateEnd(final Date dateEnd) {
    this.dateEnd = sanitizeEndDate(dateEnd);
  }

  private Date sanitizeEndDate(final Date dateEnd) {
    Date retVal = dateEnd;
    if (dateEnd != null) {
      Calendar c = Calendar.getInstance();
      c.setTime(dateEnd);
      c.set(Calendar.HOUR, 11);
      c.set(Calendar.AM_PM, Calendar.PM);
      c.set(Calendar.MINUTE, 59);
      c.set(Calendar.SECOND, 59);
      retVal = c.getTime();
    }
    return retVal;
  }

  private Date sanitizeFromDate(final Date dateFrom) {
    Date retVal = dateFrom;
    if (dateFrom != null) {
      Calendar c = Calendar.getInstance();
      c.setTime(dateFrom);
      c.set(Calendar.HOUR, 0);
      c.set(Calendar.AM_PM, Calendar.AM);
      c.set(Calendar.MINUTE, 0);
      c.set(Calendar.SECOND, 0);
      retVal = c.getTime();
    }
    return retVal;
  }
  
  public void setFacturaA(boolean facturaA) {
    this.facturaA = facturaA;
  }

  public void setFacturaB(boolean facturaB) {
    this.facturaB = facturaB;
  }

  public void setRemito(boolean remito) {
    this.remito = remito;
  }

  public void setNoFact(boolean notFact) {
    this.noFact = notFact;
  }

  public String getPayedOption() {
    return payedOption;
  }

  public void setPayedOption(String payedOption) {
    this.payedOption = payedOption;
  }

}
